package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.PageResult;
import com.itheima.mapper.ArticlesMapper;
import com.itheima.pojo.Articles;
import com.itheima.service.ArticlesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ArticlesServiceImpl implements ArticlesService {

    @Autowired
    private ArticlesMapper articlesMapper;

    /**
     * keyword=%E7%94%9F%E5%91%BD&state
     * @param page
     * @param pagesize
     * @param keyword
     * @return
     */
    @Override
    public PageResult findPage(Integer page, Integer pagesize, String keyword,Integer state) {
        LambdaQueryWrapper<Articles> wrapper = new LambdaQueryWrapper<>();
        if (keyword!=null){
            wrapper.like(Articles::getTitle,keyword);

        }

        if (state!=null){
            wrapper.eq(Articles::getState,state);
        }
        IPage<Articles> p=new Page<>(page,pagesize);
        IPage<Articles> articlesIPage = articlesMapper.selectPage(p, wrapper);

        PageResult pageResult = new PageResult();
        pageResult.setCounts((int) articlesIPage.getTotal());
        pageResult.setPage((int) articlesIPage.getCurrent());
        pageResult.setPages((int) articlesIPage.getPages());
        pageResult.setPagesize((int) articlesIPage.getSize());
        pageResult.setItems(articlesIPage.getRecords());

        return pageResult;
    }

    @Override
    public void add(Articles articles) {
        articlesMapper.insert(articles);
    }

    @Override
    public void deleteById(Integer id) {
        articlesMapper.deleteById(id);
    }

    @Override
    public void updateState(Integer id, Integer state) {
        Articles articles = articlesMapper.selectById(id);
        articles.setState(state);

        articlesMapper.updateById(articles);
    }

    @Override
    public void updateById(Integer id, Articles articles) {
        LambdaUpdateWrapper<Articles> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Articles::getId,id);
        articlesMapper.update(articles,wrapper);
    }

    @Override
    public Articles findById(Integer id) {
        Articles articles = articlesMapper.selectById(id);
        return articles;
    }
}
